package ie.lawlor.amvc.example.explorer.orderlist;

import ie.lawlor.amvc.event.Event;
import ie.lawlor.amvc.patterns.table.TableCellReference;
import ie.lawlor.amvc.patterns.table.TableController;
import ie.lawlor.amvc.patterns.table.TableModel;
import tmp.AmazonOrder;
import tmp.AmazonProduct;
import tmp.OrderItem;


/**
 * @author blawlor
 *
 */
public class OrderListModel extends TableModel {
	
	public OrderListModel(String name){
		super(name);
		AmazonOrder o = new AmazonOrder();
		o.setOrderId("1001");
		OrderItem orderItem = new OrderItem();
    orderItem.setSKU("123-002");
    orderItem.setQuantity(1);
		o.addOrderItem(orderItem);
		list.add(o);
		initFields();
	}
	
	private void initFields(){
		Field field = new Field(1, true);
		field.setTitle("Order Id");
		fields.add(field);
		visibleFields.add(field);
		field = new Field(2, true);
		field.setTitle("Total");
		fields.add(field);
		visibleFields.add(field);
	}
	
	public void doList(Event e){
		fireUpdateView();
	}
  

  public void doChangeList(Event e){
    logger.debug("About to update the list to be " + e.getPayload());
    if (e.getPayload() instanceof AmazonProduct){
      AmazonProduct product = (AmazonProduct)e.getPayload();
      list = product.getOrders();
      fireUpdateView();
    }
  }    
	
	public void doSelect(Event e) {
		TableCellReference cell = (TableCellReference)e.getPayload();
		if (selectedRow != cell.row || selectedColumn != cell.column){
			selectedRow = cell.row;
			selectedColumn = cell.column;
			if (selectedRow > -1){
				selectedObject = list.get(selectedRow);
			}
			fire(getController().getEvent(TableController.SELECTION_CHANGED_EVENT),((AmazonOrder)selectedObject).getOrderItems());
			fireUpdateView();
		}
	}
	
	public int getMaxWidth(int columnIndex) {
		switch (columnIndex){
		   case 0: return 12; 
		   case 1: return 100; 
		   default: return 10;
		}
	}

	public int getNumberOfFields() {
		return 2;
	}

	public int getPreferredWidth(int columnIndex) {
		switch (columnIndex){
		   case 0: return 12; 
		   case 1: return 25; 
		   default: return 10;
		}
	}

	public Object getValueAt(int x, int y) {
		AmazonOrder o = (AmazonOrder)list.get(x);
		switch (y){
		   case 0: return o.getOrderId(); 
		   case 1: return o.getOrderTotal();
		   default: return null;
		}
	}
}
